package com.example.librarygames;

import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
	Library dbHelper = null;
	SQLiteDatabase db = null;
	
	ArrayAdapter<String> LibraryAdapter = null;
	protected void atualizarLista(){
		db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("SELECT * FROM LIBRARY", null);
		while (!cursor.isAfterLast()){
			// Long id = cursor.getLong(0);
			String nome = cursor.getString(1);
			LibraryAdapter.add(nome);
			cursor.moveToNext();
		}
		cursor.close();
		db.close();
		dbHelper.close();
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ArrayList<String> library = new ArrayList<String>();
		LibraryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, library);
		ListView listViewDisciplinas = (ListView) findViewById(R.id.listView1);
		listViewDisciplinas.setAdapter(LibraryAdapter);
		try{
			dbHelper = new Library(getApplicationContext());
			atualizarLista();
		}catch (Exception ex){
			new AlertDialog.Builder(this).
			setMessage(ex.getMessage()).setPositiveButton("Ok", null).show();
		}
		
	}
	
	public void adicionark (View view){
		try{
			EditText editTextNovo = (EditText) findViewById(R.id.editText1);
			String library = editTextNovo.getText().toString();
			db = dbHelper.getWritableDatabase();
			db.execSQL("INSERT INTO LIBRARY(NOME) VALUES('"+library+"')");
			db.close();
			dbHelper.close();
			editTextNovo.setText("");
			
			LibraryAdapter.add(library);
		}catch (Exception ex) {
			new AlertDialog.Builder(this)
			.setMessage(ex.getMessage()).setPositiveButton("OK", null).show();
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
